/**
 * storage 相关操作
 */

/**
 * @description 存储
 * @param {String} key 键名
 * @param {String} value 键值
 * @param {Number} expire 有效期，单位：秒，默认：1秒
 */
const set = (key, value, expire = 1) => {
  expire *= 1000;
  const data = {
    value,
    expire: new Date().getTime() + expire
  };
  window.localStorage.setItem(key, JSON.stringify(data));
};

/**
 * @description 移除
 * @param {String} key 键名
 */
const remove = key => {
  window.localStorage.removeItem(key);
};

/**
 * @description 清空
 */
const clear = () => {
  window.localStorage.clear();
};

/**
 * @description 读取
 * @param {String} key 键名
 */
const get = key => {
  const value = window.localStorage.getItem(key);
  if (value) {
    const data = JSON.parse(value);
    if (!data || data.expire < new Date().getTime()) {
      remove(key);
      return '';
    }
    return data.value;
  } else {
    return '';
  }
};

export { get, set, remove, clear };
